#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        std::cerr<<"Uage:"<<argv[0]<<" server_ip server_port"<<std::endl;
        return 1;
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    //1.创建socket
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        std::cerr << "socket create error" << std::endl;
        return 2;
    }

    //2.客户端不需要手动显示绑定ip和端口
    //3.填写服务器信息
    struct sockaddr_in server;//包含netinet/in.h 和 arpa/inet.h
    memset(&server,0,sizeof(server));
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);
    server.sin_family = AF_INET;

    //4.发送信息给服务器
    while(true)
    {
        std::string input;
        std::cout<<"Please Enter:";
        std::getline(std::cin,input);

        int n = sendto(sockfd,input.c_str(),input.size(),0,(struct sockaddr*)&server,sizeof(server));
        (void)n;

        //5.接收服务器返回的信息
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len;
        int m = recvfrom(sockfd,buffer,sizeof(buffer),0,(struct sockaddr*)&peer,&len);
        if(m > 0)
        {
            buffer[m] = 0;
            std::cout<<buffer<<std::endl;
        }

    }

    return 0;
}